import React from 'react'
import Child from './Child'
import Child1 from './Child1'

class Comment extends React.Component {
  state = {
    count: 99,
    username: '',
    text: '',
    comment: [
      {
        id: 1,
        username: '小明',
        text: '123'
      },
      {
        id: 2,
        username: '小红',
        text: '打造的地方'
      }
    ]
  }

  // 通过 if 语句实现条件渲染
  renderList = () => {
    if (!this.state.comment.length) {
      return (
        <div> 评论内容为空</div> 
        )
    } else {
      return (
        <ul className="list">
          {this.state.comment.map(item => {
            return (
              <li key={item.id}>
                <div>评论人: { item.username }</div>
                <div>评语: { item.text }</div>
              </li>
            )
          })}
        </ul>
      )
    }
  }

  formHandler = e => {
    const {name, value} = e.target
    this.setState({
      [name]: value
    })
  }

  sendMsg = () => {
    const { username, text } = this.state
    if (username.trim() === '' || text.trim() === '') {
      this.setState({
        // 清空数据
        username: '',
        text: '',
      })
      return alert('请输入用户名和评论')
    }
    const commenItem = {
      id: Date.now(),
      username,
      text
    }
    this.setState({
      // 添加数据
      comment: [commenItem, ...this.state.comment],
     
    })
  }

  getParam = (data) => {
    console.log(data)
    this.setState({
      count: data
    })
  }
  render() {
    return (
      <div>
        {/* 评论结构 */}
        <div className="form">
          <div>
            评论人: <input type="text"  name="username" onChange={this.formHandler} value={this.state.username}/>
          </div>
          <div>
            评论内容:<textarea cols="30" rows="10" name="text" onChange={this.formHandler} value={this.state.text}></textarea>
          </div>
          <div>
            <button onClick={this.sendMsg}>发表评论</button>
          </div>
        </div>
        {this.renderList()}
        {/* 兄弟传值: 1子 --> 父 --> 2子 */}
        <Child fn={ this.getParam }/>
        <Child1 count={this.state.count} />
      </div>
    );
  }
}

export default Comment